<template>
  <div class="activity-list-container">
    <h2>活动列表</h2>
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="活动名称">
          <el-input v-model="filterForm.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="filterForm.type" placeholder="请选择活动类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="线上" value="1" />
            <el-option label="线下" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="filterForm.status" placeholder="请选择活动状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待审核" value="0" />
            <el-option label="已发布" value="1" />
            <el-option label="进行中" value="2" />
            <el-option label="已结束" value="3" />
            <el-option label="已取消" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="activity-cards">
      <el-row :gutter="20">
        <el-col :span="8" v-for="activity in filteredActivities" :key="activity.activityId">
          <el-card class="activity-card">
            <img :src="activity.coverUrl || 'https://via.placeholder.com/300x200'" class="activity-image" />
            <div class="activity-info">
              <h3>{{ activity.title }}</h3>
              <div class="activity-meta">
                <div class="meta-item">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDate(activity.startTime) }} 至 {{ formatDate(activity.endTime) }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ activity.location || '线上活动' }}</span>
                </div>
                <div class="meta-item">
                  <el-icon><Coin /></el-icon>
                  <span>{{ activity.pointsAward || 0 }}积分</span>
                </div>
                <div class="meta-item">
                  <el-icon><User /></el-icon>
                  <span>{{ activity.currentParticipants }}/{{ activity.maxParticipants || '不限' }}人</span>
                </div>
              </div>
              <div class="activity-status">
                <el-tag :type="getStatusTag(activity.status)">
                  {{ activity.status }}
                </el-tag>
              </div>
              <div class="activity-actions">
                <el-button size="small" @click="showDetail(activity)">详情</el-button>
                <el-button
                    size="small"
                    type="primary"
                    @click="signUp(activity.activityId)"
                    :disabled="activity.status !== '已发布' ||
              (activity.maxParticipants && activity.currentParticipants >= activity.maxParticipants) ||
              isSignedUp(activity.activityId)">
                  {{ isSignedUp(activity.activityId) ? '已报名' : '报名' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="dialogVisible" title="活动详情" width="50%">
      <div v-if="currentActivity" class="activity-detail">
        <h3>{{ currentActivity.title }}</h3>
        <div class="detail-row">
          <span class="label">活动类型：</span>
          <span>{{ currentActivity.activityType === 1 ? '线上' : '线下' }}</span>
        </div>
        <div class="detail-row">
          <span class="label">活动时间：</span>
          <span>{{ formatDateTime(currentActivity.startTime) }} 至 {{ formatDateTime(currentActivity.endTime) }}</span>
        </div>
        <div class="detail-row" v-if="currentActivity.signupEndTime">
          <span class="label">报名截止：</span>
          <span>{{ formatDateTime(currentActivity.signupEndTime) }}</span>
        </div>
        <div class="detail-row" v-if="currentActivity.location">
          <span class="label">活动地点：</span>
          <span>{{ currentActivity.location }}</span>
        </div>
        <div class="detail-row">
          <span class="label">参与人数：</span>
          <span>{{ currentActivity.currentParticipants }}/{{ currentActivity.maxParticipants || '不限' }}人</span>
        </div>
        <div class="detail-row">
          <span class="label">积分奖励：</span>
          <span>{{ currentActivity.pointsAward || 0 }}积分</span>
        </div>
        <div class="detail-row">
          <span class="label">活动状态：</span>
          <el-tag :type="getStatusTag(currentActivity.status)">
            {{ currentActivity.status }}
          </el-tag>
        </div>
        <div class="detail-row">
          <span class="label">活动描述：</span>
          <div class="description" v-html="currentActivity.content"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, Location, Coin, User } from '@element-plus/icons-vue'
import axios from 'axios'


const filterForm = reactive({
  name: '',
  type: '',
  status: ''
})

const activityList = ref([])
const userActivities = ref([]) // 存储用户已报名的活动
const currentActivity = ref(null)
const dialogVisible = ref(false)

// 获取活动列表
const getActivityList = async () => {
  try {
    const res = await axios.get(BASE_URL+'/api/v1/activities/list', {
      params: {
        pageNum: 1,
        pageSize: 100
      }
    })
    activityList.value = res.data.data.list.map(item => ({
      ...item,
      status: getStatusText(item.status),
      statusCode: item.status
    }))
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  }
}

// 获取用户已报名的活动
const getMyActivities = async () => {
  try {
    const username = localStorage.getItem('username')
    if (username) {
      const res = await axios.get(BASE_URL+'/api/v1/activities/myActivities', {
        params: { username }
      })
      userActivities.value = res.data.data
    }
  } catch (error) {
    console.error('获取我的活动失败', error)
  }
}

// 报名方法
const signUp = async (activityId) => {
  try {
    const username = localStorage.getItem('username')
    if (!username) {
      ElMessage.error('请先登录')
      return
    }

    const userRes = await axios.get(BASE_URL+'/api/v1/users/getUserByUsername', {
      params: { username }
    })

    if (!userRes.data.data?.userId) {
      ElMessage.error('获取用户信息失败')
      return
    }

    const data = {
      activityId: activityId,
      userId: userRes.data.data.userId,
      username: username
    }

    await axios.post(BASE_URL+'/api/v1/activities/join', data, {
      headers: { 'Content-Type': 'application/json' }
    })

    ElMessage.success('报名成功')
    // 刷新数据
    await getActivityList()
    await getMyActivities()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '报名失败')
  }
}

// 检查是否已报名
const isSignedUp = (activityId) => {
  return userActivities.value.some(activity => activity.activityId === activityId)
}

// 活动状态文本转换
const getStatusText = (status) => {
  switch(status) {
    case 0: return '待审核'
    case 1: return '已发布'
    case 2: return '进行中'
    case 3: return '已结束'
    case 4: return '已取消'
    default: return '未知状态'
  }
}

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 状态标签类型
const getStatusTag = (status) => {
  switch(status) {
    case '已发布': return 'success'
    case '进行中': return 'primary'
    case '已结束': return 'info'
    case '已取消': return 'danger'
    default: return ''
  }
}

// 初始化加载
onMounted(() => {
  getActivityList()
  getMyActivities()
})

// 筛选活动
const filteredActivities = computed(() => {
  return activityList.value.filter(activity => {
    const nameMatch = !filterForm.name || activity.title.includes(filterForm.name)
    const typeMatch = !filterForm.type || activity.activityType == filterForm.type
    const statusMatch = !filterForm.status || activity.statusCode == filterForm.status
    return nameMatch && typeMatch && statusMatch
  })
})
</script>

<style scoped>
.activity-list-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.activity-cards {
  margin-top: 20px;
}

.activity-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.activity-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.activity-image {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

.activity-info {
  padding: 15px;
}

.activity-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.activity-meta {
  margin: 10px 0;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.meta-item .el-icon {
  margin-right: 8px;
  color: #409eff;
}

.activity-status {
  margin: 10px 0;
}

.activity-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.activity-detail {
  padding: 10px;
}

.activity-detail h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}

.detail-row {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-row .label {
  font-weight: bold;
  width: 100px;
  flex-shrink: 0;
}

.description {
  flex: 1;
  line-height: 1.6;
  white-space: pre-wrap;
}
</style>